//
//  ViewController.m
//  网络请求 9.6
//
//  Created by 伍银荣 on 2017/9/6.
//  Copyright © 2017年 WYR. All rights reserved.
//

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    
    
    [self doGet];
    [self doPost];
    [self doDownload];
    
}

//get请求
-(void)doGet
{
        //get请求
        NSString *string = @"http://ipad-bjwb.bjd.com.cn/DigitalPublication/publish/Handler/APINewsList.ashx?date=20151031&startRecord=1&len=5&udid=1234567890&terminalType=Iphone&cid=213";
        NSURL *url = [NSURL URLWithString:string];
        //创建网络请求
        NSURLRequest *request = [NSURLRequest requestWithURL:url];
    
        //ios9之后使用的方法（推荐）
        NSURLSession *sesstion = [NSURLSession sharedSession];
        __block NSString *result = @"";
        NSURLSessionDataTask *task = [sesstion dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
            if (!error) {
                result = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
                NSLog(@"返回正确：%@",result);
            }
        }];
        //启动任务(执行任务)
        [task resume];
    
        //发送请求(异步请求，在主线程中请求)
        [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
            //请求到的数据长度大于0并且无错误
            if ([data length] > 0 && connectionError == nil) {
                NSString *html = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
                 NSLog(@"data = %@",data);
                NSLog(@"数据：%@",html);
            }
            NSLog(@"请求到数据了");
        }];
}

//post请求
-(void)doPost
{
    
        //post请求
        NSString *stringUrl = @"http://ipad-bjwb.bjd.com.cn/DigitalPublication/publish/Handler/APINewsList.ashx";
        NSURL *url2 = [NSURL URLWithString:stringUrl];
        //设置请求方式
        NSMutableURLRequest *mutableRequest = [NSMutableURLRequest requestWithURL:url2];
        [mutableRequest setHTTPMethod:@"POST"];
        //设置参数
        NSString *dataString = @"date=20151031&startRecord=1&len=5&udid=1234567890&terminalType=Iphone&cid=213";
        [mutableRequest setHTTPBody:[dataString dataUsingEncoding:NSUTF8StringEncoding]];
        //创建session对象发送请求
        NSURLSession *session2 = [NSURLSession sharedSession];
        //建立请求的任务
        NSURLSessionDataTask *task2 = [session2 dataTaskWithRequest:mutableRequest completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
            NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:NULL];
            NSLog(@"NSUrlSession = %@",dict);
               }];
        [task2 resume];
 
}

//下载请求
-(void)doDownload
{
    //下载
    NSString *string = @"http://ipad-bjwb.bjd.com.cn/DigitalPublication/publish/Handler/APINewsList.ashx?date=20151031&startRecord=1&len=5&udid=1234567890&terminalType=Iphone&cid=213";
    NSURL *url = [NSURL URLWithString:string];
    //创建session对象
    NSURLSession *session = [NSURLSession sharedSession];
    
    //创建下载的任务
    NSURLSessionDownloadTask *downloadTask = [session downloadTaskWithURL:url completionHandler:^(NSURL * _Nullable location, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        if (!error) {
            //创建下载保存文件路径
            NSURL *targetUrl = [NSURL fileURLWithPath:@"/Users/wuyinrong/Deskto p/myJson.json"];
            NSFileManager *fileManager = [NSFileManager defaultManager];
            //确定完全路径
            NSString *fullPath = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)lastObject] stringByAppendingPathComponent:response.suggestedFilename];
            NSLog(@"%@__",fullPath);
            [fileManager copyItemAtURL:location toURL:targetUrl error:nil];
            NSLog(@"location:%@",location);
            
        }
    }];
    [downloadTask resume];

}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
